package com.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.constant.RedisKey;
import com.dao.BookDao;
import com.dto.BookDTO;
import com.dto.BookResponsibilityDTO;
import com.po.RecordPO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.po.BookPO;
import com.po.BookResponsibilityPO;
import com.util.HttpClientUtil;
import com.util.Md5Util;
import com.util.RedisUtil;
import com.util.RestException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author linyukun
 * @date 2022/7/7 19:10
 */
@Service
public class BookServiceImpl {

    @Autowired
    private BookDao bookDao;

    @Autowired
    private RecordServiceImpl recordServiceImpl;

    @Autowired
    private RedisUtil redisUtil;


     /**
       * 根据类型获取图书列表
       * @author linyukun
       * @date 2022-07-07 19:12
     */
    public List<BookPO> getBookListByTypeId(long typeId){
        return bookDao.getBookListByTypeId(typeId);
    }

    
     /**
       * 获取图书列表
       * @author linyukun
       * @date 2022-07-09 14:45
     */
    public PageInfo getBookList(BookDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo(bookDao.getBookList(dto));
    }

    /**
     * 获取图书列表用户
     * @author linyukun
     * @date 2022-10-22 11:33
     */
    public PageInfo getBookListUser(BookDTO dto) {
        String key = RedisKey.BOOK_LIST + Md5Util.getMd5Len32(
                dto.getNameOrId() +  "_" +
                        dto.getNameAndId() + "_" +
                        dto.getPageNum() + "_" +
                        dto.getPageSize() + "_" );
        ValueOperations<String, String> operations = redisUtil.opsForValue();//获得redis的操作对象
        boolean hasKey = redisUtil.hasKey(key);
        if (hasKey) {//如果存在key
            return JSON.parseObject(redisUtil.get(key), new TypeReference<PageInfo<BookPO>>() {});
        }else{
            PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
            PageInfo result = new PageInfo(bookDao.getBookList(dto));
            operations.set(key,JSON.toJSONString(result),30, TimeUnit.MINUTES);//30分钟
            return result;
        }
    }

    
     /**
       * 添加书籍
       * @author linyukun
       * @date 2022-07-09 16:00
     */
    public Long addBook(BookDTO dto) {
        this.checkAddAndEditBookInfo(dto);
        //判断isbn是否已经存在了
        List<BookPO> existBooks = bookDao.getBookByIsbn(dto.getIsbn());
        if(!CollectionUtils.isEmpty(existBooks)){
            throw new RestException("该isbn号已经存在了");
        }
        Long bookId = bookDao.addBook(dto);
        this.saveBookResponeibility(dto.getId(),dto);
        redisUtil.deleteByPrex(RedisKey.BOOK_LIST);
        return bookId;
    }



    /**
     * 编辑图书
     * @author linyukn
     * @date 2022-07-09 17:27
     */
    @Transactional
    public Long editBook(BookDTO dto) {
        this.checkAddAndEditBookInfo(dto);
        if(ObjectUtils.isEmpty(dto.getId())){
            throw new RestException("请传递id");
        }
        //判断isbn是否已经存在了
        List<BookPO> existBooks = bookDao.getBookByIsbn(dto.getIsbn());
        if(!CollectionUtils.isEmpty(existBooks)){
            existBooks.stream().forEach(ele ->{
                if(!ele.getIsbn().equals(dto.getIsbn())){
                    throw new RestException("该isbn号已经被其他书籍占有了");
                }
            });
        }
        BookPO bookPo = bookDao.getBookById(dto);
        if(ObjectUtils.isEmpty(bookPo)){
            throw new RestException("找不到数据");
        }
        if(dto.getVersion().intValue() != bookPo.getVersion().intValue() ){
            throw new RestException("该条数据已经被人修改了，请重新刷新页面");
        }

        bookDao.editBook(dto);
        this.saveBookResponeibility(dto.getId(),dto);
        return dto.getId();
    }

    
     /**
       * 维护图书的责任者信息
       * @author linyukun
       * @date 2022-07-11 11:02
     */
    public void saveBookResponeibility(Long bookId,BookDTO dto){
        if(!ObjectUtils.isEmpty(bookId)){//如果不为空
            bookDao.deleteBookResponsibilityById(bookId);
            List<BookResponsibilityDTO> mainResponsibilitys = dto.getMainResponsibilitys();
            List<BookResponsibilityDTO> noMainResponsibilitys = dto.getNoMainResponsibilitys();
            //主要责任人
            int order = 1;
            if(!CollectionUtils.isEmpty(mainResponsibilitys)){
                for(BookResponsibilityDTO ele : mainResponsibilitys){
                    ele.setBookId(bookId);
                    ele.setIsMain(1);
                    ele.setSort(order);
                    order++;
                }
            }
            order = 1;
            //次要责任人
            if(!CollectionUtils.isEmpty(noMainResponsibilitys)){
                for(BookResponsibilityDTO ele : noMainResponsibilitys){
                    ele.setBookId(bookId);
                    ele.setIsMain(0);
                    ele.setSort(order);
                    order++;
                }
            }
            if(!CollectionUtils.isEmpty(mainResponsibilitys)){
                bookDao.addBookResponsibility(mainResponsibilitys);
            }
            if(!CollectionUtils.isEmpty(noMainResponsibilitys)){
                bookDao.addBookResponsibility(noMainResponsibilitys);
            }
        }
    }


     /**
       * 校验添加图书或者修改图书的信息的方法
       * @author linyukn
       * @date 2022-07-09 17:27
     */
    public void checkAddAndEditBookInfo(BookDTO dto){
        if(StringUtils.isBlank(dto.getBookName())){
            throw new RestException("请传递书籍名称");
        }
        if(StringUtils.isBlank(dto.getPublish())){
            throw new RestException("请传递出版社");
        }
        if(StringUtils.isBlank(dto.getAuthor())){
            throw new RestException("请传递作者");
        }
        if(ObjectUtils.isEmpty(dto.getStock())){
            throw new RestException("请传递库存");
        }
        if(ObjectUtils.isEmpty(dto.getPrice())){
            throw new RestException("请传递单价");
        }
        if(StringUtils.isEmpty(dto.getIsbn())){
            throw new RestException("请传递isbn");
        }
    }



    /**
      * 根据书籍id获取书籍信息
      * @author linyukn
      * @date 2022-07-11 9:06
    */
    public BookPO getBookById(BookDTO dto) {
        if(ObjectUtils.isEmpty(dto.getId())){
            throw new RestException("请传递书籍名称");
        }
        BookPO result = bookDao.getBookById(dto);

        // 获取图书的负责人信息
        List<BookResponsibilityPO> mainResponsibilitys = bookDao.getBookResponsibilityListByBookIdAndIsMain(dto.getId() , 1);
        List<BookResponsibilityPO> noMainResponsibilitys = bookDao.getBookResponsibilityListByBookIdAndIsMain(dto.getId() , 0);
        result.setMainResponsibilitys(new ArrayList<>());
        result.setNoMainResponsibilitys(new ArrayList<>());
        if(!CollectionUtils.isEmpty(mainResponsibilitys)){
            result.setMainResponsibilitys(mainResponsibilitys);
        }
        if(!CollectionUtils.isEmpty(noMainResponsibilitys)){
            result.setNoMainResponsibilitys(noMainResponsibilitys);
        }
        return result;
    }

    
     /**
       * 删除书籍的方法
       * @author linyukun
       * @date 2022-07-11 19:12
     */
    public Object delBook(BookDTO dto) {
        if(ObjectUtils.isEmpty(dto.getId())){
            throw new RestException("请传递id");
        }
        //这本书是不是借出去了
        List<RecordPO> records = recordServiceImpl.getRecordListByBookId(dto.getId());
        if(!CollectionUtils.isEmpty(records)){
            throw new RestException("该书籍尚有借出的记录，不能删除");
        }
        Integer i = bookDao.delteBookById(dto);
        //删除所有的库存
        bookDao.delteBookStockByBookId(dto);

        //region 删除图书推荐
        bookDao.deleteBookRecommendByBookId(dto);
        //endregion 删除图书推荐

        redisUtil.deleteByPrex(RedisKey.BOOK_LIST);
        return i;

    }

    public Object reptileList() {
        return bookDao.reptileList();
    }

    public Object getRemoteIsbn(BookDTO dto) {
        String isbn = dto.getIsbn();
        if(StringUtils.isBlank(isbn)){//如果isbn是空的

        }
        isbn = isbn.replace("-","");
        String result = HttpClientUtil.fetchDataPost("https://opac.gzlib.org.cn/opac/api/search?q=" + isbn + "&searchType=standard&isFacet=true&view=standard&searchWay=isbn&rows=10&sortWay=score&sortOrder=desc&hasholding=1&searchWay0=marc&logical0=AND&wt=json", new HashMap<>());// 发送短链短信的接口
        System.out.println(result);
        JSONObject resultJSONObject = JSON.parseObject(result);
        if(!ObjectUtils.isEmpty(resultJSONObject)){
            JSONArray docs = resultJSONObject.getJSONObject("response").getJSONArray("docs");
            if(!ObjectUtils.isEmpty(docs)){
                String authorMeta = (String)docs.getJSONObject(0).get("author_meta");//作者
                String pubDate = (String)docs.getJSONObject(0).get("pubdate_meta");//出版日期
                String publisherMeta = (String)docs.getJSONObject(0).get("publisher_meta");//出版社
                String pageMeta = (String)docs.getJSONObject(0).get("page_meta");//页数
                String titleName = (String)docs.getJSONObject(0).get("title_meta");//书名
            }
        }
        return null;

    }
}
